package fragments;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Rect;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.example.administrator.baseproject.BaseFragment;
import com.example.administrator.newxlmedical.R;
import com.example.administrator.newxlmedical.UserActivity;

import java.util.ArrayList;
import java.util.List;

import adapters.UserManageAdapter;
import beans.NewUserInfoBean;
import beans.PutAndDeleteBean;
import beans.UserInfoBean;
import beans.UserManageBean;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import constants.Constants;
import constants.HandlerConstant;
import custom.MyDialog;
import customhandler.MyHandler;
import dialogs.UserManageEditDialog;
import dialogs.UserManageEditSucDialog;
import dialogs.UserManageFingerDialog;
import dialogs.UserManageIrisDialog;
import dialogs.UserManagePasswordDialog;
import dialogs.UserManageRegisterInfoDialog;
import netframe.GetRetrofit;
import netframe.NetAddress;
import register.FingerprintRegisterClass;
import register.IrisRegisterClass;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import singleton.SingletonClass;
import utils.FormateUtils;
import utils.MediaPlayerUtils;
import utils.ObjectSaveUtil;
import utils.ScreenUtils;
import utils.TimeUtil;
import utils.UserManageSortUtils;
import utils.ViewUtil;
import view.DragView;

/**
 * A simple {@link Fragment} subclass.
 */
public class UserManageFragment extends BaseFragment implements UserManageAdapter.OnClickListener {

    @BindView(R.id.rv_user_manage)
    RecyclerView recyclerView;
    @BindView(R.id.fl_user_manage_empty)
    FrameLayout flEmpty;
    Unbinder unbinder;
    @BindView(R.id.tv_user_manage_id)
    TextView tvId;
    @BindView(R.id.iv_user_manage_id)
    ImageView ivId;
    @BindView(R.id.rl_user_manage_id)
    RelativeLayout rlId;
    @BindView(R.id.tv_user_manage_name)
    TextView tvName;
    @BindView(R.id.iv_user_manage_name)
    ImageView ivName;
    @BindView(R.id.rl_user_manage_name)
    RelativeLayout rlName;
    @BindView(R.id.dv_user_manage_search)
    DragView dvSearch;
    @BindView(R.id.et_user_manage_search)
    EditText etSearch;
    @BindView(R.id.tv_user_manage_search)
    TextView tvSearch;
    @BindView(R.id.tv_user_manage_cancel)
    TextView tvCancel;
    @BindView(R.id.rl_user_manage_search)
    RelativeLayout rlSearch;

    private MyHandler allHandler;
    private MediaPlayer mediaPlayer;
    private UserManageAdapter adapter;
    private List<UserManageBean> list = new ArrayList<>();
    private List<UserManageBean> allList = new ArrayList<>();
    private List<UserManageBean> nomalList = new ArrayList<>();

    private boolean isSortName, isSortId;
    private int sortName, sortId;
    private boolean isChickSearch = true;
    private String[] roleType;

    private FingerprintRegisterClass fingerprintRegister;
    private IrisRegisterClass irisRegister;
    private UserManageIrisDialog irisDialog;
    private UserManageFingerDialog fingerprintDialog;
    private NewUserInfoBean.DataBean userInfoBean;
    private Call<ArrayList<UserInfoBean>> call;
    private boolean isResume;
    private boolean isFrist = true;
    private UserActivity activity;

    public UserManageFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_user_manage, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initView() {
        activity = (UserActivity) getActivity();
        allHandler = SingletonClass.getSingleton(MyHandler.class);
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        adapter = new UserManageAdapter(mContext, list);
        adapter.setOnClickListener(this);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapter);
        roleType = FormateUtils.getRoleType();
        userInfoBean = (NewUserInfoBean.DataBean) ObjectSaveUtil.readObject(mContext, Constants.USER_INFO_BEAN, Constants.USER_INFO_BEAN);
        getUserInfo("");
    }

    @Override
    protected void setListener() {

        dvSearch.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        activity.viewPager.setScanScroll(false);
                        break;

                    case MotionEvent.ACTION_MOVE:
                        isChickSearch = false;
                        break;

                    case MotionEvent.ACTION_UP:
                        activity.viewPager.setScanScroll(true);
                        if (isChickSearch) {
                            hideEmptyView();
                            dvSearch.setVisibility(View.GONE);
                            rlSearch.setVisibility(View.VISIBLE);
                            list.clear();
                            list.addAll(allList);
                            adapter.notifyDataSetChanged();
                            etSearch.setText("");
                        } else {
                            isChickSearch = true;
                        }
                        break;
                }
                return false;
            }
        });

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    private void getUserInfo(String sql) {
        StringBuilder sb = new StringBuilder();
        sb.append("select Name,UCode,Department,WorkKind,FingerprintId,ID,RoleInfoId,Enable,IDCardCode,SupplierName,")
                .append("CardPositiveImg,CardOppositeImg,QualificationsImg,LEFT(LeftImg,1) as LeftImg,LEFT(FingerprintOne,1) as FingerprintOne,")
                .append("Password,LEFT(FingerprintTwo,1) as FingerprintTwo ")
                .append("from UserInfo where (LeftImg is not null or FingerprintId is not null) and DelFlag = 0 ");
        if (!TextUtils.isEmpty(sql)) {
            sb.append("and Name like '%" + sql + "%' " + "or UCode like '%" + sql + "%'");
        }

        if (userInfoBean.getRoleInfoId() != 5) {
            sb.append(" and RoleInfoId !=5");
        }
        list.clear();
        nomalList.clear();
        hideEmptyView();
        showLoadingView(flEmpty);
        call = GetRetrofit.getInstance().getUserInfo(NetAddress.token, NetAddress.machineCode, sb.toString());
        call.enqueue(new Callback<ArrayList<UserInfoBean>>() {
            @Override
            public void onResponse(Call<ArrayList<UserInfoBean>> call, Response<ArrayList<UserInfoBean>> response) {
                hideLoadingView();
                ArrayList<UserInfoBean> body = response.body();
                if (body != null) {
                    int size = body.size();
                    if (size > 0) {
                        for (int i = 0; i < size; i++) {
                            UserInfoBean userInfoBean = body.get(i);
                            UserManageBean bean = new UserManageBean();
                            bean.setNumber(userInfoBean.getUCode());
                            bean.setName(userInfoBean.getName());
                            bean.setDepartment(userInfoBean.getDepartment());
                            bean.setWorkKind(userInfoBean.getWorkKind());
                            bean.setFingerprintId(userInfoBean.getFingerprintId());
                            bean.setUserInfoId(userInfoBean.getID());
                            int roleInfoId = userInfoBean.getRoleInfoId();
                            bean.setRoleId(roleInfoId);
                            bean.setEnable(userInfoBean.isEnable());
                            bean.setIdNumber(userInfoBean.getIDCardCode());
                            bean.setSupplierName(userInfoBean.getSupplierName());
                            bean.setCardPositiveImg(userInfoBean.getCardPositiveImg());
                            bean.setCardOppositiveImg(userInfoBean.getCardOppositeImg());
                            bean.setQualificationsImg(userInfoBean.getQualificationsImg());
                            bean.setLeftImg(userInfoBean.getLeftImg());
                            bean.setFingerOne(userInfoBean.getFingerprintOne());
                            bean.setFingerTwo(userInfoBean.getFingerprintTwo());
                            bean.setPassword(userInfoBean.getPassword());
                            if (roleInfoId > 0 && roleInfoId <= roleType.length) {
                                bean.setRole(roleType[roleInfoId - 1]);
                            }
                            bean.setId(userInfoBean.getID());
                            list.add(bean);
                            nomalList.add(bean);
                        }
                        if (isFrist) {
                            isFrist = false;
                            allList.addAll(list);
                        }
                        adapter.notifyDataSetChanged();
                    } else {
                        if (list.size() == 0) {
                            showEmptyView(flEmpty);
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<ArrayList<UserInfoBean>> call, Throwable t) {
                Log.e(TAG, "onFailure: " + t.getMessage());
                if (flEmpty != null) {
                    showEmptyView(flEmpty);
                    hideLoadingView();
                }
            }
        });
    }

    private int updateAllList(int id) {
        for (int i = 0; i < allList.size(); i++) {
            UserManageBean userManageBean = allList.get(i);
            if (userManageBean.getId() == id) {
                return i;
            }
        }
        return 0;
    }

    @Override
    public void onChangeIris(final int position) {
        final UserManageBean userManageBean = list.get(position);
        new UserManageRegisterInfoDialog(mContext, R.style.dialog, userManageBean, new UserManageRegisterInfoDialog.OnClickListener() {
            @Override
            public void onSure(UserManageRegisterInfoDialog dialog) {
                dialog.dismiss();
                irisDialog = new UserManageIrisDialog(mContext, R.style.dialog);
                irisDialog.show();
                irisRegister = new IrisRegisterClass(mContext) {
                    @Override
                    public void irisNetWork(String image) {
                        userManageBean.setLeftImg(image.substring(0));
                        allList.get(updateAllList(userManageBean.getId())).setLeftImg(image.substring(0));
                        updateIris("set LeftImg = '" + image + "', RightImg = '" + image + "',ChangeTime = '" + TimeUtil.getMillisecondDate() + "' where ID = " + userManageBean.getId());
                    }

                    @Override
                    public void irisFailure() {

                    }
                };
            }
        }).show();
    }

    @Override
    public void onChangeFingerprint(int position) {
        final UserManageBean userManageBean = list.get(position);
        new UserManageRegisterInfoDialog(mContext, R.style.dialog, list.get(position), new UserManageRegisterInfoDialog.OnClickListener() {
            @Override
            public void onSure(UserManageRegisterInfoDialog dialog) {
                dialog.dismiss();
                fingerprintDialog = new UserManageFingerDialog(mContext, R.style.dialog);
                fingerprintDialog.show();
                fingerprintRegister = new FingerprintRegisterClass(mContext) {
                    @Override
                    public void fingerprintNetWork(String fingerprintUserId, String fingerprintFeature) {
                        userManageBean.setFingerOne(fingerprintFeature.substring(0));
                        allList.get(updateAllList(userManageBean.getId())).setFingerOne(fingerprintFeature.substring(0));
                        Log.e(TAG, "指纹注册成功: 1");
                        updateFingerprint("set FingerprintOne = '" + fingerprintFeature + "',ChangeTime = '" + TimeUtil.getMillisecondDate() + "' where ID = " + userManageBean.getId());
                    }
                };
            }
        }).show();
    }

    @Override
    public void onChangeFingerprint2(int position) {
        final UserManageBean userManageBean = list.get(position);
        new UserManageRegisterInfoDialog(mContext, R.style.dialog, list.get(position), new UserManageRegisterInfoDialog.OnClickListener() {
            @Override
            public void onSure(UserManageRegisterInfoDialog dialog) {
                dialog.dismiss();
                fingerprintDialog = new UserManageFingerDialog(mContext, R.style.dialog);
                fingerprintDialog.show();
                fingerprintRegister = new FingerprintRegisterClass(mContext) {
                    @Override
                    public void fingerprintNetWork(String fingerprintUserId, String fingerprintFeature) {
                        userManageBean.setFingerTwo(fingerprintFeature.substring(0));
                        allList.get(updateAllList(userManageBean.getId())).setFingerTwo(fingerprintFeature.substring(0));
                        Log.e(TAG, "指纹注册成功: 2");
                        updateFingerprint("set FingerprintTwo = '" + fingerprintFeature + "',ChangeTime = '" + TimeUtil.getMillisecondDate() + "' where ID = " + userManageBean.getId());
                    }
                };
            }
        }).show();
    }

    @Override
    public void onEdit(int position) {
        final UserManageBean userManageBean = list.get(position);
        new UserManageEditDialog(mContext, R.style.dialog, userManageBean, new UserManageEditDialog.OnClickListener() {
            @Override
            public void onSure(boolean enable, UserManageEditDialog dialog) {
                userManageBean.setEnable(enable);
                allList.get(updateAllList(userManageBean.getId())).setEnable(enable);
                allHandler.sendEmptyMessage(HandlerConstant.REFRESH);
                setUserInfo(dialog, "set Enable = '" + enable + "' where ID = " + userManageBean.getId());
            }
        }).show();

    }

    @Override
    public void onChangePassword(int position) {
        final UserManageBean userManageBean = list.get(position);

        new UserManagePasswordDialog(mContext, R.style.dialog, new UserManagePasswordDialog.OnClickListener() {
            @Override
            public void onModify(String password, UserManagePasswordDialog dialog) {
                userManageBean.setPassword(password);
                allList.get(updateAllList(userManageBean.getId())).setPassword(password);
                setUserInfo(dialog, "set Password = '" + password + "' where ID = " + userManageBean.getId());
            }
        }).show();
    }

    @Override
    public void onDelete(final int position) {
        final UserManageBean userManageBean = list.get(position);
        final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("提示 :");
        builder.setMessage("确定删除此用户？");
        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                list.remove(position);
                allList.remove(updateAllList(userManageBean.getId()));
                setUserInfo(null, "set DelFlag = '" + 1 + "' where ID = " + userManageBean.getId());
            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });

        builder.show();
    }

    private void setUserInfo(final MyDialog dialog, String sql) {
        GetRetrofit.getInstance().putUserInfo(NetAddress.token, NetAddress.machineCode, sql)
                .enqueue(new Callback<PutAndDeleteBean>() {
                    @Override
                    public void onResponse(Call<PutAndDeleteBean> call, Response<PutAndDeleteBean> response) {
                        PutAndDeleteBean body = response.body();
                        if (body != null && body.getAffectRowCount() > 0) {
                            if (dialog != null) {
                                dialog.dismiss();
                            }
                            new UserManageEditSucDialog(mContext, R.style.dialog, new UserManageEditSucDialog.OnClickListener() {
                                @Override
                                public void onSure(UserManageEditSucDialog dialog) {
                                    dialog.dismiss();
                                    adapter.notifyDataSetChanged();
                                }
                            }).show();

                        }
                    }

                    @Override
                    public void onFailure(Call<PutAndDeleteBean> call, Throwable t) {

                    }
                });
    }

    private void updateIris(String sql) {
        Call<PutAndDeleteBean> call = GetRetrofit.getInstance().postUserInfo(NetAddress.token, NetAddress.machineCode, sql);
        call.enqueue(new Callback<PutAndDeleteBean>() {
            @Override
            public void onResponse(Call<PutAndDeleteBean> call, Response<PutAndDeleteBean> response) {
                irisRegister.releaseIris();
                irisDialog.dismiss();
                adapter.notifyDataSetChanged();
                new UserManageEditSucDialog(mContext, R.style.dialog, new UserManageEditSucDialog.OnClickListener() {
                    @Override
                    public void onSure(UserManageEditSucDialog dialog) {
                        dialog.dismiss();
                    }
                }).show();
            }

            @Override
            public void onFailure(Call<PutAndDeleteBean> call, Throwable t) {
                irisRegister.releaseIris();
            }
        });
    }

    private void updateFingerprint(String sql) {
        Call<PutAndDeleteBean> call = GetRetrofit.getInstance().postUserInfo(NetAddress.token, NetAddress.machineCode, sql);
        call.enqueue(new Callback<PutAndDeleteBean>() {
            @Override
            public void onResponse(Call<PutAndDeleteBean> call, Response<PutAndDeleteBean> response) {
                fingerprintDialog.dismiss();
                adapter.notifyDataSetChanged();
                new UserManageEditSucDialog(mContext, R.style.dialog, new UserManageEditSucDialog.OnClickListener() {
                    @Override
                    public void onSure(UserManageEditSucDialog dialog) {
                        dialog.dismiss();
                    }
                }).show();
            }

            @Override
            public void onFailure(Call<PutAndDeleteBean> call, Throwable t) {

            }
        });
    }

    @Override
    protected void onHandleMessage(Message msg) {
        super.onHandleMessage(msg);
        switch (msg.what) {
            case HandlerConstant.REFRESH_NET:
                list.clear();
                nomalList.clear();
                getUserInfo("");
                allHandler.sendEmptyMessage(HandlerConstant.REFRESH);
                break;

            case HandlerConstant.FINGERPRINT_REGISTER_FIRST_RETURN:
                if (isResume) {
                    fingerprintDialog.getFingerIcon().setImageResource(R.mipmap.zw1st);
                    MediaPlayerUtils.playSound(mContext, R.raw.fingerprint_register_up);
                }
                break;

            case HandlerConstant.FINGERPRINT_REGISTER_SECOND:
                if (isResume) {
                    Log.e("GGG", "onHandleMessage: FINGERPRINT_REGISTER_SECOND");
                    MediaPlayerUtils.playSound(mContext, R.raw.fingerprint_register_down);
                }
                break;

            case HandlerConstant.FINGERPRINT_REGISTER_SECOND_RETURN:
                if (isResume) {
                    fingerprintDialog.getFingerIcon().setImageResource(R.mipmap.zw2ed);
                    MediaPlayerUtils.playSound(mContext, R.raw.fingerprint_register_up);
                }
                break;

            case HandlerConstant.FINGERPRINT_REGISTER_THIRD:
                if (isResume) {
                    MediaPlayerUtils.playSound(mContext, R.raw.fingerprint_register_down);
                }
                break;

            case HandlerConstant.FINGERPRINT_REGISTER_THIRD_RETURN:
                if (isResume) {
                    fingerprintDialog.getFingerIcon().setImageResource(R.mipmap.zw3rd);
                }
                break;
        }
        if (fingerprintRegister != null) {
            fingerprintRegister.onHandlerMess(msg);
        }
    }

    @Override
    public void onUnVisiable() {
        super.onUnVisiable();
        isResume = false;
    }

    @Override
    public void onVisiable() {
        super.onVisiable();
        isResume = true;
    }

    @OnClick({R.id.rl_user_manage_id, R.id.rl_user_manage_name, R.id.dv_user_manage_search, R.id.tv_user_manage_search, R.id.tv_user_manage_cancel})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_user_manage_id:
                sort(2);
                break;
            case R.id.rl_user_manage_name:
                sort(1);
                break;
            case R.id.tv_user_manage_search:
                ScreenUtils.closeKeybord(etSearch,mContext);
                String search = etSearch.getText().toString();
                if (!TextUtils.isEmpty(search)) {
                    getUserInfo(search);
                }
                rlSearch.setVisibility(View.GONE);
                dvSearch.setVisibility(View.VISIBLE);
                break;
            case R.id.tv_user_manage_cancel:
                ScreenUtils.closeKeybord(etSearch,mContext);
                rlSearch.setVisibility(View.GONE);
                dvSearch.setVisibility(View.VISIBLE);
                break;
        }
    }

    private void sort(int type) {
        if (type == 1) { // 按物品名排序
            if (sortName != 2) {
                sortName++;
                isSortName = !isSortName;
                UserManageSortUtils.sortUserManageName(list, isSortName);
            } else {
                clearSortDate();
                list.clear();
                list.addAll(nomalList);
            }
        } else {
            sortName = 0;
            isSortName = false;
        }
        if (type == 2) {
            if (sortId != 2) {
                sortId++;
                isSortId = !isSortId;
                UserManageSortUtils.sortUserManageId(list, isSortId);
            } else {
                clearSortDate();
                list.clear();
                list.addAll(nomalList);
            }
        } else {
            sortId = 0;
            isSortId = false;
        }

        ViewUtil.setSortColor(mContext, tvName, ivName, sortName);
        ViewUtil.setSortColor(mContext, tvId, ivId, sortId);
        adapter.notifyDataSetChanged();
    }

    private void clearSortDate() {
        sortName = 0;
        sortId = 0;
    }

}
